# -*- coding: utf-8 -*-
from django.core.management.base import BaseCommand
from enbook import settings
from enbook.geo.models import GeoDb 
from time import sleep
# Скрипт импортирует в MySQL БД геоданные о городах (России), которые находятся в файле (RU.txt)
# Файл с геоданными взят с сайта http://download.geonames.org/export/dump/ 

class Command(BaseCommand):
    help = 'Import or update geo database from file geodb/RU.txt'

    def handle(self, *args, **options):
        file = open(settings.FILESTORAGE+'geodb/RU.txt');
        citiesLines = file.readlines()
        file.close()
        record_count = 0
        print 'purge all record in geo database...'
        geo = GeoDb()
        geo.empty_data()
        print 'done.'
        print 'importing geonames from file to database...'
        sql = 'INSERT INTO geo_db (geoname_id,geoname,lat,lng) VALUES '
        points = []
        for cityLine in citiesLines:
            fields = cityLine.split('\t')
            altNames = fields[3]
            if len(altNames) > 0:
                geoId = fields[0]
                lat = float(fields[4])
                lng = float(fields[5])
                altNamesList = altNames.split(',')
                for geoPoint in altNamesList:
                    points.append(("(%s,'%s',%f,%f)" % (geoId,geoPoint.replace("'","\\'"),lat,lng)))
                    record_count += 1
                    if record_count > 200:
                        sql_portion = sql + ','.join(points)
                        geo.execute_raw_sql(sql_portion)
                        points = []
                        record_count = 0
                        print '*',
        geo.execute_raw_sql("COMMIT;")
        print '\nDone. elements: ',len(citiesLines)